package se.mbaeumer.fxtodo.core.handler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import se.mbaeumer.fxtodo.core.model.Context;
import se.mbaeumer.fxtodo.db.DatabaseHandler;

public class ContextHandler {
	private static final ContextHandler INSTANCE = new ContextHandler();
	private ContextHandler(){};
	public static ContextHandler getInstance(){return INSTANCE;}
	
	private List<Context> contexts;
	public void importContext(DatabaseHandler dbh, Context context) {
		dbh.importContext(context);
	}
	
	public List<Context> loadContextsFromDB(DatabaseHandler dbh){
		this.contexts = dbh.getContexts();
		return this.contexts; 
	}

	public Context updateContext(DatabaseHandler dbh, Context context) throws SQLException {
		if (context.getId() == -1){
			dbh.createContext(context);
		}else{
			dbh.updateContext(context);
		}
		
		return null;
	}

	public void deleteContexts(DatabaseHandler dbh, int contextId) {
		dbh.deleteContexts(contextId);
	}

	public List<Context> getContexts() {
		return this.contexts;
	}

	public Context getContext(DatabaseHandler dbh, int id) {
		return dbh.getContextByID(id);
	}
	
	public Context getDummyContext(){
		//TODO: Use constants instead of hard-coded strings
		Context context = new Context.ContextBuilder().
				id(-1).
				title("<New>").
				description("<New>").
				created(new Date()).
				build();
		return context;
	}

	public void setContexts(List<Context> contexts) {
		this.contexts = contexts;
	}
	
	public List<String> getContextTitles(DatabaseHandler dbh){
		this.contexts = this.loadContextsFromDB(dbh);
		List<String> contextTitles = new ArrayList<String>();
		for (Context c:this.contexts){
			contextTitles.add(c.getTitle());
		}
		return contextTitles;
	}
	
	public int getContextIdByTitle(DatabaseHandler dbh, String title){
		return dbh.getContextIDByTitle(title);
	}
}
